import { CloseOutlined } from '@ant-design/icons';
import { Button, Tooltip } from 'antd';
import { useEffect, useState } from 'react';
import type { Station } from '../../Mapless/index.d';
import Singleton from '../../Mapless/Singleton';
import styles from './index.module.less';

type StationsClickPanelProps = {
  stations: Station[] | undefined | null;
  onSelected?: (stations: Station[] | undefined | null) => void;
  onClose?: () => void;
};

const StationsClickPanel = (props: StationsClickPanelProps) => {
  const { stations, onSelected, onClose } = props;
  const [isAnimated, setIsAnimated] = useState(false);
  const [isClosing, setIsClosing] = useState(false);

  // 计算环形布局的位置 - 基于容器大小自适应
  const containerSize = 300; // 与CSS中.circle的宽高保持一致
  const radius = containerSize * 0.32; // 圆的半径（自适应，占容器大小的25%）
  const center = { x: containerSize / 2, y: containerSize / 2 }; // 圆心坐标（居中）

  useEffect(() => {
    // 当stations从空变为有内容时，触发动画
    if (stations && stations.length > 0 && !isAnimated && !isClosing) {
      setTimeout(() => {
        setIsAnimated(true);
      }, 5);
    }
  }, [stations, isAnimated, isClosing]);

  const handleClose = () => {
    // 先触发反向动画
    setIsClosing(true);
    setIsAnimated(false);

    // 等待动画完成后执行真正的关闭回调
    setTimeout(() => {
      setIsClosing(false);
      onClose?.();
    }, 300); // 与CSS过渡时间保持一致
  };

  const handleStationClick = (station: Station) => {
    onSelected?.([station]);
    handleClose();
  };

  const getStationIcon = (s: Station) => {
    const cate = s.category?.toLowerCase() || 'sensor';
    const stat = s.state?.toLowerCase() || 'idle';
    const strr = `${cate}${cate === 'sensor' ? 'Circle' : 'Rect'}_${stat}`;
    return Singleton.getIconUrl(strr);
  };

  // 计算当前动画状态
  const shouldAnimate = isAnimated && !isClosing;

  return (
    <div
      className={styles.container}
      style={{ width: containerSize, height: containerSize }}
      onClick={(e) => e.stopPropagation()}
    >
      <div
        className={`${styles.circle} ${shouldAnimate ? styles.animate : ''}`}
      />
      {stations?.map((station, index) => {
        // 计算每个点在圆上的角度（均匀分布）
        const angle = (index / stations.length) * 2 * Math.PI;

        // 计算每个点的坐标
        const x = center.x + radius * Math.cos(angle);
        const y = center.y + radius * Math.sin(angle);

        return (
          <Tooltip title={station.name} key={station.id}>
            <div
              key={station.id}
              className={`${styles.stationItem} ${station.selected ? styles.selected : ''}`}
              style={{
                left: shouldAnimate ? `${x}px` : `${center.x}px`,
                top: shouldAnimate ? `${y}px` : `${center.y}px`,
                transform: 'translate(-50%, -50%)',
                opacity: shouldAnimate ? 1 : 0,
                transition: 'all 0.3s ease',
              }}
              onClick={() => handleStationClick(station)}
            >
              <div
                style={{
                  width: 32,
                  height: 32,
                  background: `url(${getStationIcon(station)})`,
                  backgroundSize: 'cover',
                  cursor: 'pointer',
                }}
              />
              <div className={styles.name}>{station.name}</div>
            </div>
          </Tooltip>
        );
      })}
      <Button
        shape="circle"
        variant="outlined"
        color="primary"
        className={styles.closeBtn}
        icon={<CloseOutlined />}
        onClick={handleClose}
      />
    </div>
  );
};

export default StationsClickPanel;
